<template>
  <el-drawer
    :title="title"
    :visible.sync="drawer"
    :direction="direction"
    :before-close="handleClose"
    destroy-on-close
    custom-class="drawerClass"
    size="39%"
    @closeDrawer="closeDrawer"
  >
    <el-form ref="form" :model="entity" label-width="100px" :rules="rules">
      <el-form-item v-if="title !== '新增客户'" label="创建时间">
        <el-input v-model="entity.CreateTime" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="所属公司">
        <CompanySearchSelect
          v-model="entity.CompanyId"
          @select="CompanySelect"
        />
      </el-form-item>

      <el-form-item label="敏感词" prop="SensitiveWords">
        <el-input
          v-model="entity.SensitiveWords"
          placeholder="请输入所属公司敏感词"
        ></el-input>
      </el-form-item>
      <el-form-item label="客户编码" prop="cCusCode">
        <el-input
          v-model="entity.cCusCode"
          :disabled="this.title == '编辑'"
          placeholder="请输入客户编码"
        ></el-input>
      </el-form-item>
      <el-form-item label="客户名称" prop="cCusName">
        <el-input
          v-model="entity.cCusName"
          placeholder="请输入客户名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="账期(天)" prop="DelayDays">
        <el-input
          v-model="entity.DelayDays"
          placeholder="请输入账期(天)"
        ></el-input>
      </el-form-item>
      <el-form-item label="客户联系人" prop="cCusPerson">
        <el-input
          v-model="entity.cCusPerson"
          placeholder="请输入客户联系人"
        ></el-input>
      </el-form-item>
      <el-form-item label="联系方式" prop="cCusPhone">
        <el-input
          v-model="entity.cCusPhone"
          placeholder="请输入客户联系人电话"
        ></el-input>
      </el-form-item>
      <el-form-item label="认证方式" prop="SignType">
        <el-radio-group v-model="entity.SignType" @change="SignTypeChange">
          <!--          <el-radio-button label="4">验证码</el-radio-button>-->
          <!--          <el-radio-button label="0" :disabled="disabled0"-->
          <!--            >二要素</el-radio-button-->
          <!--          >-->
          <el-radio-button label="2" :disabled="disabled2"
            >三要素</el-radio-button
          >
          <el-radio-button label="1" :disabled="disabled1"
            >人脸识别</el-radio-button
          >
          <el-radio-button label="3" :disabled="disabled3"
            >仅微信认证</el-radio-button
          >
          <!--          <el-radio-button label="4" :disabled="disabled4"-->
          <!--            >验证码</el-radio-button-->
          <!--          >-->
        </el-radio-group>
        <el-popover
          placement="top-start"
          title="签收方式"
          width="400"
          trigger="hover"
        >
          <span>微信签收: 签收人在使用微信签收时可直接对回执单进行签收</span
          ><br />
          <span>二要素：签收人在首次签收前需进行姓名及身份证号验证;</span><br />
          <span
            >三要素：签收人在首次签收前需进行姓名、身份证号及手机号验证;</span
          ><br />
          <span>人脸识别：签收人在首次签收前需人脸识别验证验证;</span><br />
          <i slot="reference" class="el-icon-question question"></i>
        </el-popover>
        <span style="padding-right: 5px">(默认)</span>
      </el-form-item>
      <el-form-item label="发送方式" prop="SendType">
        <!--         暂时去掉方法  后续根据需求-->
        <el-radio-group v-model="entity.SendType" @change="SendTypeChange">
          <el-radio-button label="0" :disabled="disabled5"
            >微信小程序</el-radio-button
          >
          <el-radio-button label="1" :disabled="disabled6"
            >手机网页</el-radio-button
          >
        </el-radio-group>
      </el-form-item>
      <div style="display: flex">
        <el-form-item label="授权码" prop="IsAtuhcode">
          <el-radio-group v-model="entity.IsAtuhcode">
            <el-radio-button :label="true">是</el-radio-button>
            <el-radio-button :label="false">否</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="entity.IsAtuhcode" label="授权码">
          <el-input
            v-model.number.trim="entity.SmsCode"
            maxlength="6"
            placeholder="静态授权码"
          >
            <template slot="append">
              <el-button
                @click="IscheckPhoneCodeClick"
                style="background-color: #32cfaa; color: #fff"
                >生成</el-button
              >
            </template>
          </el-input>
        </el-form-item>
      </div>
      <el-form-item
        v-if="entity.SignType == 1"
        label="每次验证"
        prop="IsEveryVerify"
      >
        <el-radio-group v-model="entity.IsEveryVerify">
          <el-radio-button :label="1">是</el-radio-button>
          <el-radio-button :label="0">否</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="验证码" prop="IsCode">
        <el-radio-group v-model="entity.IsCode">
          <el-radio-button :label="true">是</el-radio-button>
          <el-radio-button :label="false">否</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <!--      <el-form-item label="免认证" prop="NotSign">-->
      <!--        <el-radio-group v-model="entity.NotSign">-->
      <!--          <el-radio-button :label="1">是</el-radio-button>-->
      <!--          <el-radio-button :label="0">否</el-radio-button>-->
      <!--        </el-radio-group>-->
      <!--      </el-form-item>-->

      <el-form-item label="省/直辖市">
        <el-select
          v-model="entity.cProvince"
          placeholder="请选择省/直辖市"
          @change="changeProvince"
        >
          <el-option
            v-for="item in ProvinceList"
            :key="item.Id"
            :value="item.Id"
            :label="item.Name"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="市">
        <el-select
          v-model="entity.cCity"
          placeholder="请选择市"
          @change="changeCity"
        >
          <el-option
            v-for="item in CityList"
            :key="item.Id"
            :value="item.Id"
            :label="item.Name"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="区">
        <el-select v-model="entity.cCounty" placeholder="请选择区">
          <el-option
            v-for="item in CountyList"
            :key="item.Id"
            :value="item.Id"
            :label="item.Name"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="地址" prop="cCusAddress">
        <el-input
          v-model="entity.cCusAddress"
          type="textarea"
          :autosize="{ minRows: 4 }"
        ></el-input>
      </el-form-item>
      <!-- <el-form-item label="启用授权码" prop="cCusAddress">
        <el-switch v-model="entity.ISsignCode"></el-switch>
      </el-form-item> -->

      <!--      <el-form-item label="签章">-->
      <!--        <el-upload-->
      <!--          class="avatar-uploader"-->
      <!--          action="https://jsonplaceholder.typicode.com/posts/"-->
      <!--          :show-file-list="false"-->
      <!--          :on-success="handleAvatarSuccess"-->
      <!--          :before-upload="beforeAvatarUpload"-->
      <!--        >-->
      <!--          <img-->
      <!--            class="avatar"-->
      <!--            v-if="entity.CustomerSign"-->
      <!--            :src="entity.CustomerSign"-->
      <!--          />-->
      <!--          <i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
      <!--        </el-upload>-->
      <!--      </el-form-item>-->
    </el-form>
    <div style="height: 50px"></div>
    <div
      :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '5px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 99999,
      }"
    >
      <el-button @click="drawer = false">取消</el-button>
      <el-button type="primary" :loading="btnLoading" @click="handleSubmit"
        >保存</el-button
      >
    </div>
  </el-drawer>
</template>

<script>
import CompanySearchSelect from "@/components/CompanySearchSelect.vue";
export default {
  components: {
    CompanySearchSelect,
  },
  props: {
    parentObj: { type: Object },
  },
  data() {
    return {
      disabled0: false, //二要素禁用
      disabled1: false, //人脸识别禁用
      disabled2: false, //三要素禁用
      disabled3: false, //仅微信禁用
      disabled4: false, //验证码
      disabled5: false, //微信小程序
      disabled6: false, //手机网页
      backgroundColor1: "#ccc",
      backgroundColor3: "",
      drawer: false,
      direction: "rtl",
      // sign: "",
      entity: {
        SignType: 3,
      },
      CustomerSign: "",
      rules: {
        cCusName: [
          { required: true, message: "请输入客户名称", trigger: "blur" },
        ],
        cCusCode: [
          { required: true, message: "请输入客户编号", trigger: "blur" },
        ],
        SendType: [
          { required: true, message: "请选择发送方式", trigger: "change" },
        ],
        SignType: [
          { required: true, message: "请选择认证方式", trigger: "change" },
        ],
        IscheckPhone: [
          {
            required: true,
            message: "请选择是否开启授权码",
            trigger: "change",
          },
        ],
        // IsEveryVerify: [
        //   {
        //     required: true,
        //     message: "请选择是否开始每次验证",
        //     trigger: "change",
        //   },
        // ],
        cProvince: [
          { required: true, message: "请选择省/直辖市", trigger: "change" },
        ],
        cCity: [{ required: true, message: "请选择市", trigger: "change" }],
        SmsCode: [
          { required: true, message: "请输入静态验证码", trigger: "blur" },
        ],
      },
      btnLoading: false,
      title: "",
      ProvinceList: [],
      CityList: [],
      CountyList: [],
    };
  },
  methods: {
    SendTypeChange(e) {
      console.log("发送方式改变---", e);
    },
    // 关闭抽屉回调
    closeDrawer() {
      console.log("关闭抽屉回调", this.entity);
    },
    // 自动生成随机数 数字+小写字母
    generateRandomCode() {
      let result = "";
      const characters = "0123456789abcdefghijklmnopqrstuvwxyz";
      const charactersLength = characters.length;
      for (let i = 0; i < 8; i++) {
        result += characters.charAt(
          Math.floor(Math.random() * charactersLength)
        );
      }
      return result;
    },
    // 生成授权码
    IscheckPhoneCodeClick() {
      this.entity.SmsCode = this.generateRandomCode();
      console.log("生成授权码", this.entity.SmsCode, this.entity);
    },

    // 认证方式选择改变回调
    SignTypeChange(event) {
      if (event == 0 || event == 2) {
        this.entity.SendType = "";
        // 如果点击的是二要素 或者三要素    通过微信或者手机网页都可以
        this.disabled5 = false;
        this.disabled6 = false;
      } else if (event == 1) {
        // 如果点击的是人脸识别  只能是通过手机网页获取 禁用仅微信 自动选中 通过手机网页获取
        this.entity.SendType = 1;
        this.disabled5 = true;
        this.disabled6 = false;
      } else if (event == 3) {
        this.entity.SendType = 0;
        //   如果点击的是仅微信认证    只能是通过微信获取  禁用人脸  自动选中通过微信获取
        this.disabled5 = false;
        this.disabled6 = true;
      }
    },
    // 公司选择
    CompanySelect(row) {
      console.log(row);
    },
    handleAvatarSuccess(res, file) {},
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      if (!isJPG) {
        return this.$message.error("请选择JPG/PNG格式图片");
      }
      var _this = this;
      var reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = function (e) {
        // 图片base64化
        var newUrl = this.result; //图片路径
        _this.$set(_this.entity, "CustomerSign", newUrl);
      };
    },
    init() {
      this.drawer = true;
      let numArr = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
      let str = "";
      for (let i = 0; i < 6; i++) {
        str += numArr[parseInt(Math.random() * 10)];
      }

      // this.entity.SmsCode = str;
      // this.$set(this.entity, "ISsignCode", true);
      // this.$set(this.entity, "SmsCode", str);
      this.$nextTick(() => {
        this.$refs["form"].clearValidate();
      });
      this.entity = {
        // ISsignCode: true,
        //  授权码方式默认不开启
        // IscheckPhone: false,
        //  每次是否验证默认不开启
        IsEveryVerify: 0,
        // ***************************************** 默认初始化空  否则校验不会清空****************************************
        SendType: "",
        SignType: "",
        // ***************************************** 默认初始化空  否则校验不会清空****************************************
        SmsCode: str,
      };
    },
    openForm(Id, CompanyId) {
      this.init();
      if (CompanyId) {
        this.entity.CompanyId = CompanyId;
      }
      this.title = "新增客户";
      // 发送方式和认证方式初始化
      this.entity.SendType = "";
      this.entity.SignType = "";
      // 验证码默认赋值
      this.entity.IsCode = 0;
      this.disabled0 = false;
      this.disabled1 = false;
      this.disabled2 = false;
      this.disabled3 = false;

      if (Id) {
        this.title = "编辑客户";
        this.getTheData(Id);
      }
      this.getProvinceList();
    },
    handleClose(done) {
      done();
    },
    getTheData(id) {
      this.$http.post("/BO/CustomerInfo/GetTheData", { id }).then((res) => {
        if (res.Success) {
          this.entity = res.Data;
          // 处理客户编码有时显示undefind情况
          if (this.entity.cCusCode === "undefined") this.entity.cCusCode = "";
          if (this.entity.cProvince) this.getCityList(this.entity.cProvince);
          if (this.entity.cCity) this.getCountyList(this.entity.cCity);
          // 时间格式化
          this.entity.CreateTime = this.timeFormat(
            this.entity.CreateTime,
            "YYYY-MM-DD HH:mm:ss"
          );
          console.log("获取签收方式详情结果", this.entity);
          //   判断认证方式是否存在
          if (this.entity.SignType == null) {
            // 不渲染
            this.entity.SignType = "";
            this.entity.SendType = "";
          } else {
            let SignType = this.entity.SignType.toString();
            this.entity.SignType = SignType;
            console.log("转换签收方式", SignType);
          }
          // 根据认证方式判断发送方式
          if (this.entity.SignType == 0 || this.entity.SignType == 2) {
            //   如果认证方式为二要素  三要素    微信和手机网页都可
            this.disabled5 = false;
            this.disabled6 = false;
          } else if (this.entity.SignType == 1) {
            //   如果认证方式为人脸识别  只能手机网页
            this.disabled5 = true;
            this.disabled6 = false;
          } else {
            //   如果认证方式为仅微信  只能微信小程序
            this.disabled5 = false;
            this.disabled6 = true;
          }

          console.log("签收方式时==", this.entity.SignType);
          //  是否开启授权码默认不开启
          if (
            this.entity.IsAtuhcode == null ||
            this.entity.IsAtuhcode === "null"
          ) {
            this.entity.IsAtuhcode = false;
          }
          //  是否开启验证码默认不开启
          if (this.entity.IsCode == null || this.entity.IsCode === "null") {
            this.entity.IsCode = false;
          }
          // 处理发送方式返回null情况回显
          if (this.entity.SendType == null || this.entity.SendType === "null") {
            this.entity.SendType = "";
          }
          // 如果没有返回授权码  自动生成
          if (this.entity.SmsCode == null || this.entity.SmsCode === "null") {
            this.entity.SmsCode = this.generateRandomCode();
          }
          //   判断每次验证
        } else {
          this.$message.error(res.Msg);
        }
      });
    },
    changeProvince(e) {
      console.log("选择得省是", e);
      this.$set(this.entity, "cCity", "");
      this.$set(this.entity, "cCounty", "");
      this.getCityList(e);
    },
    changeCity(e) {
      this.$set(this.entity, "cCounty", "");
      this.getCountyList(e);
    },
    // 省列表
    getProvinceList() {
      this.$http
        .post("/Base_BasicData/Base_District/GetDataListByPId?pId=0", {})
        .then((resJson) => {
          console.log("获取省列表数据", resJson);
          this.ProvinceList = resJson.Data;
        });
    },
    // 市列表
    getCityList(id) {
      this.$http
        .post("/Base_BasicData/Base_District/GetDataListByPId?pId=" + id, {})
        .then((resJson) => {
          this.CityList = resJson.Data;
        });
    },
    // 区列表
    getCountyList(id) {
      this.$http
        .post("/Base_BasicData/Base_District/GetDataListByPId?pId=" + id, {})
        .then((resJson) => {
          this.CountyList = resJson.Data;
        });
    },
    handleSubmit() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return;
        }
        this.btnLoading = true;

        let newEntity = JSON.parse(JSON.stringify(this.entity));

        // 判断是否认证方式选择了人脸识别  如果不是  初始化每次验证
        if (
          newEntity.SignType == 0 ||
          newEntity.SignType == 2 ||
          newEntity.SignType == 3
        ) {
          newEntity.IsEveryVerify = 0;
        }
        console.log(
          "编辑保存了-newEntitynewEntitynewEntitynewEntitynewEntitynewEntitynewEntity----",
          newEntity
        );
        this.$http.post("/BO/CustomerInfo/SaveData", newEntity).then((res) => {
          this.btnLoading = false;
          if (res.Success) {
            this.$message.success("操作成功");
            this.parentObj.getDataList();
            this.drawer = false;
          } else {
            this.$message.error(res.Msg);
          }
        });
      });
    },
  },
};
</script>

<style>
.drawerClass {
  padding: 10px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  background: #fff;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 200px;
  line-height: 200px;
  text-align: center;
}
.avatar {
  width: 200px;
  height: 200px;
  display: block;
}
</style>
